<!--
 * @description  : 市管-坐标采集
 * @descriptionDetail: 市管-坐标采集
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-10-20 16:43:02
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
      <view class="right-icon" @click="help">
        帮助
      </view>
    </theme-navbar>
    <!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="fContent" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <view class="content">
      <view :style="{width: getContainerWidth(), height: containerHeight}" id="container"></view>
      <view class="y-location" ref="yLocRef">
        <view style="color: #000;font-size: 30rpx;">
          {{ marketGis.gisName || '无名称' }}
        </view>
        <view style="font-size: 26rpx;color: #585656;margin-top: 20rpx;">
          {{ marketGis.gisDesc }}
        </view>
        <view class="popup-submit-btns">
          <u-button class="u-btn" plain type="primary" @click="showOrHideRetailers">
            {{ isShowRetailer? "隐藏周边零售户":"显示周边零售户" }}
          </u-button>
          <u-button class="u-btn" type="primary" @click="collectCurrMarker">
            采集当前坐标
          </u-button>
        </view>
      </view>
      <view class="floating-button" :class="[isShowAllGis ? 'floating-button-press':'']" style="padding: 0 14px;" :style="{bottom:floatingBottom}" @click="isShowAllGis?closeAllGis():showAllGis()">
        {{ isShowAllGis?"关闭\n已采":"显示\n已采" }}
      </view>
    </view>
  </view>
</template>

<script>
	import {
		AMapMixin
	} from '@/common/AMapMixin.js';
	import certificateService from '@/service/certificate/certificate.service';
	import zjCommonService from '@/service/common/common.service';
	import fabButton from '@/components/uni-fab.vue';

	import {
		SET_MAP_LAT_LON
	} from '@/config/setting.config.js';
	export default {
		components: {
			fabButton
		},
		onLoad() {
			this.hasDefaultGeo = false;
		},
		mixins: [AMapMixin],
		data() {
			return {
				shopIcon: require('@/static/check/shop.png'),
				currPosition: {},
				retailerIcon: undefined, // 零售户icon
				retailer: undefined, // 零售户信息
				marketGis: {
					gisDesc: '',
					gisName: '',
				}, // 采集坐标信息
				isShowAllGis: false, // 是否显示所有已采集坐标
				isShowRetailer: false, // 是否显示周边零售户
				overlayGroups: null, // 已采坐标覆盖物组
				retailerOverlayGroups: null, // 周边零售户覆盖物组
				clickedCollectedGisMarker: null, // 点击的已采集坐标marker
				keys: [
					'creator',
					'distance',
					'gisDesc',
					'gisName',
					'gisSubtype',
					'gisSubtypeName',
					'gisType',
					'gisTypeName',
					'gisUuid',
					'isActive',
					'latitude',
					'longitude',
					'orgCode',
					'orgUuid',
				],
				yLocHeight: 100,
				fContent: [{
					iconPath: require('@/static/help.png'),
					selectedIconPath: require('@/static/help.png'),
					text: '帮助',
					active: false,
				}],
			};
		},
		computed: {
			containerHeight() {
				let p = this.$u.sys().windowHeight - 44 - this.$u.sys().statusBarHeight - this.yLocHeight + 'px';
				// #ifdef H5-DINGDING
				p = this.$u.sys().windowHeight - this.$u.sys().statusBarHeight - this.yLocHeight + 'px';
				// #endif
				return p;
			},
			floatingBottom() {
				return this.yLocHeight + 16 + 'px';
			},
		},
		watch: {
			'marketGis.gisName': {
				handler: function(newValue, oldValue) {
					setTimeout(() => {
						this.yLocHeight = this.$refs.yLocRef.$el.clientHeight;
					}, 100);
				},
			},
			'marketGis.gisDesc': {
				handler: function(newValue, oldValue) {
					setTimeout(() => {
						this.yLocHeight = this.$refs.yLocRef.$el.clientHeight;
					}, 100);
				},
			},
		},
		mounted() {
			this.init();
		},
		methods: {
			init() {
				this.setRightBtns();
				// this.$modal.showLoading('地图加载中...');
			},
			initAmap() {
				this.retailerIcon = new AMap.Icon({
					size: new AMap.Size(24, 24), // 图标尺寸
					image: this.shopIcon, // Icon的图像
					imageSize: new AMap.Size(24, 24), //,
				});
				let self = this;
				this.geolocation = new AMap.Geolocation({
					enableHighAccuracy: true, // 是否使用高精度定位，默认:true
					timeout: 10000, // 超过10秒后停止定位，默认：5s
					// buttonPosition:'RB',    //定位按钮的停靠位置
					buttonOffset: new AMap.Pixel(5, 10), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
					// zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
					content: '<img src="//a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>',
				});
				// #ifdef H5-ONLY
				self.curPos = SET_MAP_LAT_LON;
				self.currPosition.latitude = SET_MAP_LAT_LON[1];
				self.currPosition.longitude = SET_MAP_LAT_LON[0];
				self.setMapInstance(SET_MAP_LAT_LON);
				// #endif
				// #ifdef H5-DINGDING || H5-WECHAT || H5-EMP
				this.$deviceApi.geolocation().then(
					(pos) => {
						self.curPos = [pos.longitude, pos.latitude];
						self.currPosition.latitude = pos.latitude;
						self.currPosition.longitude = pos.longitude;
						self.setMapInstance([pos.latitude, pos.longitude]);
					},
					(error) => {
						self.justInitMap();
					}
				);
				// #endif
			},
			setRightBtns() {
				// 设置右侧标题
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight('帮助', () => {
					this.help();
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.help();
				}
			},
			getContainerWidth() {
				return this.$u.sys().windowWidth + 'px';
			},
			confirm() {
				this.backPrev({
					paramKey: 'pos',
					param: this.currPosition,
				});
			},
			setMapInstance(cords) {
				if (!this.hasInited) return;
				let self = this;
				self.curCords = new AMap.LngLat(cords[0], cords[1]);
				self.amap = new AMap.Map('container', {
					center: self.curCords,
					zoom: 18,
					resizeEnable: true,
					scrollWheel: true,
					zoomEnable: true,
					mapStyle: 'amap://styles/fresh',
				});
				this.$modal.hideLoading();
				this.loadPlugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.OverView', 'AMap.MapType', 'AMap.Geolocation'], () => {
					// 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
					self.amap.addControl(new AMap.Scale());
					self.amap.addControl(new AMap.ToolBar());
					self.amap.addControl(self.geolocation);
				});
				// 地图缩放
				this.amap.on('zoomend', function(ev) {
					self.closeInfoWindow();
				});
				// 地图移动
				this.amap.on('moveend', (ev) => {
					self.currPosition.latitude = self.amap.getCenter().lat;
					self.currPosition.longitude = self.amap.getCenter().lng;
					if (self.isShowRetailer || self.isShowAllGis) {
						return;
					}
					self.amap.clearMap();
					// me.closeInfoWindow();
					let icon = new AMap.Icon({
						size: new AMap.Size(19, 28), // 图标尺寸
						image: require('@/static/market/new-location.png'),
						imageSize: new AMap.Size(19, 28), // 根据所设置的大小拉伸或压缩图片
					});
					let marker = new AMap.Marker({
						position: self.amap.getCenter(),
						icon: icon,
						offset: new AMap.Pixel(-9, -28),
						draggable: true, // 设置是否可以拖拽
						cursor: 'move',
						raiseOnDrag: true, // 设置拖拽效果
					});
					marker.setMap(self.amap);
					marker.on('dragend', (info) => {
						self.currPosition.latitude = info.lnglat.lat;
						self.currPosition.longitude = info.lnglat.lng;
						// 根据坐标查询地址信息
						self.getPosition(info.lnglat.lng, info.lnglat.lat, marker, true);
						self.clickedCollectedGisMarker = marker;
					});
				});
				this.initLocation();
			},
			/**
			 * 初始化当前位置图标
			 */
			initLocation() {
				let self = this;
				let icon = new AMap.Icon({
					size: new AMap.Size(19, 28), // 图标尺寸
					image: require('@/static/market/new-location.png'),
					// imageOffset: new AMap.Pixel(0, -60),  // 图像相对展示区域的偏移量，适于雪碧图等
					imageSize: new AMap.Size(19, 28), // 根据所设置的大小拉伸或压缩图片
				});
				let marker = new AMap.Marker({
					position: this.amap.getCenter(),
					icon: icon,
					offset: new AMap.Pixel(-9, -28),
					// 设置是否可以拖拽
					draggable: true,
					cursor: 'move',
					// 设置拖拽效果
					raiseOnDrag: true,
				});
				marker.setMap(this.amap);
				marker.on('dragend', (info) => {
					self.currPosition.latitude = info.lnglat.lat;
					self.currPosition.longitude = info.lnglat.lng;
					// 根据坐标查询地址信息
					self.getPosition(info.lnglat.lng, info.lnglat.lat, marker, true);
					self.clickedCollectedGisMarker = marker;
				});
				// 设置地图中心点
				self.amap.setCenter(new AMap.LngLat(self.currPosition.longitude, self.currPosition.latitude));
				self.getPosition(self.currPosition.longitude, self.currPosition.latitude, marker, true);
			},
			/**
			 * 根据坐标查询位置信息
			 * @param lng
			 * @param lat
			 */
			getPosition(lng, lat, marker, isShowDialog) {
				let self = this;
				AMap.plugin('AMap.Geocoder', function() {
					let geocoder = new AMap.Geocoder({
						// city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
						city: '全国',
					});
					let lnglat = [lng, lat];
					geocoder.getAddress(lnglat, function(status, result) {
						if (status === 'complete' && result.info === 'OK') {
							self.marketGis.longitude = lng;
							self.marketGis.latitude = lat;
							self.marketGis.gisName = result.regeocode.addressComponent.building || result.regeocode.addressComponent.neighborhood;
							self.marketGis.gisDesc = result.regeocode.formattedAddress;
						}
					});
				});
			},
			/**
			 * 采集当前坐标
			 */
			collectCurrMarker() {
				// this.marketGis = {};
				this.collect();
			},
			/**
			 * 显示或取消显示周边零售户
			 */
			showOrHideRetailers() {
				if (this.isShowRetailer) {
					this.retailerOverlayGroups && this.amap.remove(this.retailerOverlayGroups);
					this.isShowRetailer = false;
					// 显示拖拽图标
					this.initLocation();
				} else {
					this.query();
				}
			},
			/**
			 * 显示采集位置窗体信息
			 * @param pos
			 */
			showDialog(pos) {
				let self = this;
				let content = `<div class="gaode-info-title">${this.marketGis.gisName || '无名称'}</div>
				    <div class="gaode-info-content">地址：${this.marketGis.gisDesc}</div>`;
				let container = document.createElement('div');
				container.style.margin = '-5px';
				let btnContainer = document.createElement('div');
				btnContainer.className = 'row';
				let aBtn = document.createElement('button');
				aBtn.className = 'col button button-small button-fill';
				aBtn.innerText = '采集当前坐标';
				btnContainer.appendChild(aBtn);
				let retailBtn = document.createElement('button');
				retailBtn.className = 'col button button-small button-fill';
				retailBtn.innerText = this.isShowRetailer ? '隐藏周边零售户' : '显示周边零售户';
				btnContainer.appendChild(retailBtn);
				let infoWindow = new AMap.InfoWindow({
					content: container,
					asOrigin: false,
					asDestination: false,
					placeSearch: false,
					offset: new AMap.Pixel(0, -45),
				});
				aBtn.addEventListener('click', () => {
					self.collect();
					infoWindow.close();
					self.showDialog(new AMap.LngLat(self.marketGis.longitude, self.marketGis.latitude));
				});
				retailBtn.addEventListener('click', () => {
					if (self.isShowRetailer) {
						self.retailerOverlayGroups && self.amap.remove(self.retailerOverlayGroups);
						self.isShowRetailer = false;
						// 显示拖拽图标
						self.initLocation();
					} else {
						self.query();
					}
				});
				container.innerHTML = content;
				container.appendChild(btnContainer);
				infoWindow.open(this.amap, pos);
			},
			/**
			 * 关闭窗体信息
			 */
			closeInfoWindow() {
				this.amap.clearInfoWindow();
			},
			/**
			 * 采集
			 */
			collect() {
				if (!this.marketGis.longitude || !this.marketGis.latitude) {
					this.$modal.alert('请选择采集坐标位置');
					return;
				}
				this.setRouteParam(this.marketGis);
				this.$u.route('/pages/check/poiCollect/poiCollect');
			},
			updateBackState(param) {
				if (param.collectInfo) {
					for (let i = 0; i < this.keys.length; i++) {
						this.marketGis[this.keys[i]] = param.collectInfo[this.keys[i]];
					}
					this.closeInfoWindow();
					this.isShowAllGis && this.showCollectedGisInfo();
					this.$modal.alert('采集成功');
				}
			},
			/**
			 * 查询周边零售户
			 */
			query() {
				this.isShowRetailer = true;
				let retailerMarkers = [];
				let me = this;
				this.$modal.showLoading('正在查询周边零售户...');
				let zoom = this.amap.getZoom();
				let bounds = this.amap.getBounds();
				let req = {};
				req.longitudeLeft = bounds.southwest.lng;
				req.latitudeLeft = bounds.southwest.lat;
				req.longitudeRight = bounds.northeast.lng;
				req.latitudeRight = bounds.northeast.lat;
				req.page = 1;
				req.limit = 9999;
				certificateService
					.listRetailInScope(req)
					.then((rt) => {
						me.$modal.hideLoading();
						if (rt.success) {
							me.amap.clearMap();
							let count = rt.data.length;
							rt.data.forEach((retailer) => {
								let markerConfig = {
									title: retailer.companyName,
									icon: me.retailerIcon,
									label: null,
									position: [retailer.longitude, retailer.latitude],
								};
								if (count < 30) {
									markerConfig.label = {
										content: retailer.companyName,
										offset: new AMap.Pixel(22, 1),
									};
								}
								let marker = new AMap.Marker(markerConfig);
								marker.on('click', () => {
									me.showRetailer(retailer);
								});
								retailerMarkers.push(marker);
							});
							me.retailerOverlayGroups = new AMap.OverlayGroup(retailerMarkers);
							me.amap.add(me.retailerOverlayGroups);
						} else {
							me.$modal.alert(rt.msg);
						}
					})
					.catch((err) => {
						me.$modal.alert(rt.msg);
					});
			},
			/**
			 * 显示已采集gis坐标
			 */
			showAllGis() {
				this.$u.loading('查询已采集的坐标中...');
				this.clickedCollectedGisMarker = null;
				let markers = [];
				// 查询已采集坐标数据
				let param = {};
				let self = this;
				param.longitude = self.currPosition.longitude;
				param.latitude = self.currPosition.latitude;
				zjCommonService.getNearBy(param).then((res) => {
					this.$u.hideLoading();
					if (!res.success) return;
					let markets = res.data;
					if (!markets || markets.length == 0) {
						self.$modal.alert('没有已采集的坐标');
						return;
					}
					markets.forEach((mg, idx) => {
						let markerConfig = {
							title: mg.gisName,
							icon: new AMap.Icon({
								size: new AMap.Size(20, 24), // 图标尺寸
								image: this.getGisIconPath(mg.gisSubtype), // Icon的图像
								imageSize: new AMap.Size(20, 24),
							}),
							position: [mg.longitude, mg.latitude],
							offset: new AMap.Pixel(-8, 5),
							label: {},
						};
						if (idx < 30) {
							markerConfig.label = {
								content: mg.gisName,
								offset: new AMap.Pixel(26, 1),
							};
						}
						let marker = new AMap.Marker(markerConfig);
						marker.on('click', () => {
							self.marketGis = Object.assign(self.marketGis, mg);
							self.clickedCollectedGisMarker = marker;
							self.showCollectedGisInfo();
						});
						markers.push(marker);
					});
					self.closeInfoWindow();
					self.amap.clearMap();
					self.overlayGroups = new AMap.OverlayGroup(markers);
					self.amap.add(self.overlayGroups);
					self.isShowAllGis = true;
				});
			},
			/**
			 * 显示指定的已采集坐标信息窗体
			 * @param mg
			 */
			showCollectedGisInfo() {
				let content = `<div class="gaode-info-title">${this.marketGis.gisName}</div>
					<div class="gaode-info-content">地址：${this.marketGis.gisDesc}</div>`;
				let container = document.createElement('div');
				container.style.margin = '-5px';
				let btnContainer = document.createElement('div');
				btnContainer.className = 'row';
				let editBtn = document.createElement('button');
				editBtn.style = 'padding: 5px 10px;background-color: #1fa3ff;color: #FFF;border: none;border-radius: 5px;width:40%;';
				editBtn.innerText = '编辑';
				btnContainer.appendChild(editBtn);
				let delBtn = document.createElement('button');
				delBtn.style = 'padding: 5px 10px;background-color: #f90;;color: #FFF;border: none;border-radius: 5px;width:40%;';
				delBtn.innerText = '删除';
				btnContainer.appendChild(delBtn);
				// 编辑
				editBtn.addEventListener('click', () => {
					this.collect();
				});
				// 删除
				delBtn.addEventListener('click', () => {
					this.delCollectedGisInfo();
				});
				container.innerHTML = content;
				container.appendChild(btnContainer);

				let infoWindow = new AMap.InfoWindow({
					content: container,
					asOrigin: false,
					asDestination: false,
					placeSearch: false,
					offset: new AMap.Pixel(6, 0),
				});
				infoWindow.open(this.amap, this.clickedCollectedGisMarker.getPosition());
			},
			/**
			 * 删除指定的已采集GIS坐标
			 * @param mg
			 */
			delCollectedGisInfo() {
				let self = this;
				this.$modal.alert(
					'确认删除当前采集的坐标吗？',
					'提示',
					() => {
						self.marketGis.isActive = 0;
						zjCommonService.modifyLocation(self.marketGis).then((dr) => {
							self.$modal.alert('删除成功');
							// 删除标记及信息窗体
							self.amap.remove(self.clickedCollectedGisMarker);
							self.closeInfoWindow();
						});
					},
					'确定',
					true
				);
			},
			/**
			 * 关闭显示已采集坐标
			 */
			closeAllGis() {
				this.isShowAllGis = false;
				if (this.overlayGroups) {
					this.amap.clearMap();
					this.overlayGroups = null;
				}
				for (let i = 0; i < this.keys.length; i++) {
					this.marketGis[this.keys[i]] = '';
				}
				this.clickedCollectedGisMarker = null;
				this.initLocation();
			},
			/**
			 * 显示零售户详情
			 * @param retailer
			 */
			showRetailer(retailer) {
				// let component = new RetailerinfoComponent(retailer.retailerUuid);
				// this.view.loadController(component);
			},
			/**
			 * 帮助提示
			 */
			help() {
				!this.isShowAllGis && this.$modal.alert('拖动“气泡”图标至指定位置，点击信息窗体中的“采集当前坐标”');
				this.isShowAllGis && this.$modal.alert('点击图标，编辑或删除已采集坐标');
			},
			justInitMap() {
				this.$modal.alert('请在设备的设置中开启APP的定位权限后重新获取当前位置');
				this.amap = new AMap.Map('container', {
					showControlButton: true,
					zoom: 18,
				});
				let self = this;
				this.$modal.hideLoading();
			},
			/**
			 * 获取采集坐标的类型小图片
			 * @param {Object} gitType  gis类型
			 * @param {Object} hasLic  是否已关联
			 */
			getGisIconPath(gitType) {
				let path = '';
				if (gitType == '0101') {
					path = 'gt0101';
				} else if (gitType == '0102') {
					path = 'gt0102';
				} else if (gitType == '0103') {
					path = 'gt0103';
				} else if (gitType == '0104') {
					path = 'gt0104';
				} else if (gitType == '0105') {
					path = 'gt0105';
				} else if (gitType == '0106') {
					path = 'gt0106';
				}
				if (path != '') {
					return require('@/static/check/gis/' + path + '.png');
				} else {
					return require('@/static/check/gps.png');
				}
			},
		},
	};
</script>

<style scoped lang="scss">
	.button {
		padding: 10px;
	}

	.page {
		padding: 0;
	}

	.right-icon {
		padding: 0 25rpx;
		font-size: 30rpx;
		color: white;
	}

	#container {
		/* #ifdef H5 */
		width: 100%;
		height: 100%;
		/* #endif */
		/* #ifdef APP-PLUS */
		height: calc(100vh - 44 - var(--status-bar-height));
		margin-top: calc(44 + var(--status-bar-height));
		/* #endif */
	}

	.retailer-markers {
		width: 30%;
		position: absolute;
		top: calc(84px + env(safe-area-inset-top));
		z-index: 888;
		line-height: 38rpx;
		background-color: rgba(255, 255, 255, 1);
		margin: 0 10px;
		padding: 20rpx 20rpx;
		border-radius: 10px;
	}

	.markers-state {
		font-size: 28rpx;
		margin: 0 10rpx;
		background-color: rgba(255, 255, 255, 1);
		display: inline-flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		width: 100%;
	}

	.index-class {
		font-weight: bold;
	}

	.poi-info {
		color: #666;
		line-height: 25px;
		margin: 5px 0px;
		width: 100%;
		display: inline-flex;
		flex-direction: column;
		font-size: 28rpx;
		margin-bottom: 5rpx;
	}

	.poi-name {
		margin: 3rpx 0rpx;
	}

	.poi-price {
		display: inline-flex;
		flex-direction: row;
		align-items: center;
		margin: 3rpx 0rpx;
	}

	.poi-price-txt {
		margin-left: 28rpx;
	}

	/deep/.row {
		width: 100%;
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		margin: 3px 0px;
	}

	.poi-title {
		color: black;
		font-size: 32rpx;
	}

	.task-status-lst {
		line-height: 38rpx;
		margin: 10px;
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.item-circle-status {
		width: 4px;
		height: 16px;
		border-radius: 20%;
	}

	.item-color {
		color: #999;
		margin-left: 15px;
	}

	.cur-loc {
		position: absolute;
		bottom: 20px;
		left: 15px;
		padding: 5px;
		background: #fff;
		width: 35px;
		height: 35px;
		box-shadow: 0px 0px 0px 1px #ddd;
	}

	.y-location {
		position: fixed;
		bottom: 0;
		width: 100%;
		opacity: 0.86;
		background-color: #ffffff;
		padding: $cm-conent-padding-column $cm-content-paddng-row;
		border-top-left-radius: 25rpx;
		border-top-right-radius: 25rpx;
	}

	.floating-button {
		color: #fff;
		position: absolute;
		right: 16px;
		width: 56px;
		height: 56px;
		font-size: 20rpx;
		text-align: center;
		border-radius: 50%;
		z-index: 1500;
		overflow: hidden;
		transition-duration: 300ms;
		box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: $u-type-primary;
		border: 1px solid $u-type-primary;
	}

	.floating-button-press {
		background-color: #ffffff !important;
		color: $u-type-primary;
	}

	/deep/.amap-toolbar {
		left: 0px !important;
		bottom: 180px !important;
		right: auto !important;
	}

	/deep/.amap-geolocation-con {
		left: 10px !important;
		bottom: 50px !important;
	}
</style>
